<template>
    <div class="user">
        <el-card>
            <el-row>
                <el-col :span="24">
                    <el-button
                        type="primary"
                        size="small"
                        @click="openAddUserDialog"
                        >添加</el-button
                    >
                </el-col>
            </el-row>

            <el-table :data="list" style="width: 100%" border stripe>
                <el-table-column prop="username" label="用户名">
                </el-table-column>

                <el-table-column prop="mobile" label="手机号">
                </el-table-column>

                <el-table-column prop="email" label="邮箱"> </el-table-column>

                <el-table-column prop="sex" label="性别"> </el-table-column>

                <el-table-column prop="age" label="年龄"> </el-table-column>

                <el-table-column prop="age" label="年龄"> </el-table-column>

                <el-table-column fixed="right" label="操作">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click="openEditUserDialog(scope.row)"
                            >编辑</el-button
                        >

                        <el-button
                            type="text"
                            size="small"
                            @click="deleteUser(scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <!-- 表格分页组件 -->
            <el-pagination
                @size-change="getList"
                @current-change="getList"
                :current-page.sync="query.pagenum"
                :page-sizes="[1, 2, 5, 10, 20]"
                :page-size.sync="query.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 添加用户弹框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addUserDialogVisible"
            width="50%"
            @close="addUserDialogClosed"
        >
            <el-form
                :model="addUserForm"
                :rules="addUserFormRules"
                ref="addUserFormRef"
                label-width="100px"
                label-position="top"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>

                <el-form-item label="年龄" prop="age">
                    <el-input v-model="addUserForm.age"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-input v-model="addUserForm.sex"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户弹框 -->
        <el-dialog
            title="编辑用户"
            :visible.sync="editUserDialogVisible"
            width="50%"
            @close="editUserDialogClosed"
        >
            <el-form
                :model="editUserForm"
                :rules="editUserFormRules"
                ref="editUserFormRef"
                label-width="100px"
                label-position="top"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input
                        v-model="editUserForm.username"
                        disabled
                    ></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="editUserForm.password"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>

                <el-form-item label="年龄" prop="age">
                    <el-input v-model="editUserForm.age"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-input v-model="editUserForm.sex"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editUserDialogVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
function mobileValidator(rule, value, callback) {
    console.log('value', value);
    // 非空就不验证
    if (!value || !value.trim()) {
        callback();
        return;
    }

    if (/^1[359]\d{9}$/.test(value)) {
        callback();
    } else {
        callback(new Error('手机号格式不正确'));
    }
}

function emailValidator(rule, value, callback) {
    // 非空就不验证
    if (!value || !value.trim()) {
        callback();
        return;
    }

    // 531804271@qq.com
    if (/^\w+@\w+\.com$/.test(value)) {
        callback();
    } else {
        callback(new Error('邮箱格式不正确'));
    }
}

export default {
    data() {
        return {
            query: {
                pagenum: 1,
                pagesize: 10,
            },
            list: [],
            total: 0,
            addUserDialogVisible: false,
            addUserForm: {
                username: '',
                password: '',
                mobile: '',
                email: '',
                sex: '',
                age: '',
            },
            addUserFormRules: {
                username: [
                    {
                        required: true,
                        message: '用户名不能为空',
                        // 什么时候校验，触发时机
                        trigger: 'change',
                    },
                    {
                        min: 5,
                        max: 20,
                        message: '长度在 5 到 20 个字符',
                        trigger: 'change',
                    },
                ],
                password: [
                    {
                        required: true,
                        message: '密码不能为空',
                        // 什么时候校验，触发时机
                        trigger: 'change',
                    },
                    {
                        min: 6,
                        max: 20,
                        message: '长度在 6 到 20 个字符',
                        trigger: 'change',
                    },
                ],
                mobile: [
                    {
                        required: true,
                        message: '手机号不能为空',
                        trigger: 'change',
                    },
                    { validator: mobileValidator, trigger: 'change' },
                ],
                email: [
                    {
                        required: true,
                        message: '邮箱不能为空',
                        // 什么时候校验，触发时机
                        trigger: 'change',
                    },
                    { validator: emailValidator, trigger: 'change' },
                ],
                age: [
                    {
                        required: true,
                        message: '年龄不能为空',
                        // 什么时候校验，触发时机
                        trigger: 'change',
                    },
                ],
                sex: [
                    {
                        required: true,
                        message: '性别不能为空',
                        // 什么时候校验，触发时机
                        trigger: 'change',
                    },
                ],
            },
            editUserDialogVisible: false,
            editUserForm: {},
            editUserFormRules: {
                password: [
                    {
                        min: 6,
                        max: 20,
                        message: '长度在 6 到 20 个字符',
                        trigger: 'change',
                    },
                ],
                mobile: [{ validator: mobileValidator, trigger: 'change' }],
                email: [{ validator: emailValidator, trigger: 'change' }],
            },
        };
    },
    mounted() {
        this.getList();
    },
    methods: {
        getList() {
            this.$http.get('/users', { params: this.query }).then((res) => {
                // console.log('res', res);
                this.list = res.data.list;
                this.total = res.data.total;
            });
        },
        openEditUserDialog(row) {
            console.log('row', row);
            this.editUserDialogVisible = true;
            // 显示用户名
            this.editUserForm.id = row.id;
            this.editUserForm.username = row.username;
        },
        deleteUser(user) {
            this.$confirm(
                `此操作将永久删除《${user.username}》这个用户, 是否继续?`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                },
            )
                .then(async () => {
                    // 调用后台接口，删除该用户 get post put delete  user 表的复数 users put delete /users/:id
                    const res = await this.$http.delete(`/users/${user.id}`);
                    // 如果删除失败，提示用户
                    if (res.code !== 204) {
                        this.$message.error(res.message);
                        return;
                    }
                    // 删除成功，刷新列表
                    this.getList();
                })
                .catch(() => {});
        },
        openAddUserDialog() {
            this.addUserDialogVisible = true;
        },
        async addUser() {
            // console.log('this.addUserForm', this.addUserForm);
            const res = await this.$http.post('/users', this.addUserForm);
            // 添加用户失败
            if (res.code !== 201) {
                this.$message.error(res.message);
                return;
            }
            // 需要重新刷新用户列表
            this.getList();
            // 关闭弹框
            this.addUserDialogVisible = false;
        },
        addUserDialogClosed() {
            this.$refs.addUserFormRef.resetFields();
        },
        editUserDialogClosed() {},
        async editUser() {
            console.log('this.editUserForm', this.editUserForm);
            const params = { ...this.editUserForm };
            // console.log('params', params);
            delete params.id;
            delete params.username;
            const res = await this.$http.put(
                `/users/${this.editUserForm.id}`,
                params,
            );
            // 如果修改失败，提示用户
            if (res.code !== 200) {
                this.$message.error(res.message);
                return;
            }
            // 如果修改成功，刷新列表
            this.getList();
            // 关闭弹框
            this.editUserDialogVisible = false;
        },
    },
};
</script>

<style lang="less" scoped>
.el-table {
    margin-top: 20px;
}

.el-pagination {
    margin-top: 10px;
}
</style>
